package com.example.login.view

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ClickUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base.app.RouterPath
import com.example.common.entity.UserEntity
import com.example.common.event.BusEvent
import com.example.common.event.LiveDataBus
import com.example.common.mvi.BaseMviActivity
import com.example.login.R
import com.example.login.databinding.ActivityLoginBinding
import com.example.login.intent.AccountViewIntent
import com.example.login.state.AccountUiState
import com.example.login.vm.AccountViewModel
import com.tencent.mmkv.MMKV
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
@Route(path = RouterPath.PATH_LOGIN_PAGE)
class LoginActivity : BaseMviActivity<ActivityLoginBinding>() {
    private val mViewModel: AccountViewModel by viewModels()

    private var userName = ""
    private var password = ""
    override fun getLayoutId(): Int =R.layout.activity_login

    override fun initViews() {
        mDataBinding.ivBack.setOnClickListener {
            this@LoginActivity.finish()
        }
        mDataBinding.tvTitle.text = "登录"
        //给输入框添加监听事件
        mDataBinding.etAccount.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                userName = s.toString().trim()
            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
        mDataBinding.etPassword.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                password = s.toString().trim()
            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
        mDataBinding.tvForgetBtn.setOnClickListener {
            startActivity(Intent(this, OneLoginActivity::class.java))
        }
        //登录的点击事件
        mDataBinding.tvLoginBtn.apply {
            setOnClickListener(object : ClickUtils.OnMultiClickListener(1, 500){
                override fun onTriggerClick(v: View?) {
                    loginToServer()
                    MMKV.defaultMMKV().encode("token","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIxMzk1NTY2Nzc4OCIsImV4cCI6MTc2MDQzNTM2Nn0.0U9HHPNyp47QysmJgysCERJMOTmO7t2TPwLH3-bQl7Q")
                }

                override fun onBeforeTriggerClick(v: View?, count: Int) {
                    LogUtils.i("登录按钮被点击！！")
                }
            })
        }

        //注册新账号
        mDataBinding.tvRegisterBtn.setOnClickListener {
            ARouter.getInstance().build(RouterPath.PATH_REGISTER_PAGE).navigation()
        }

        LiveDataBus.getDefault<BusEvent>("login_page_new_account").observe(this@LoginActivity){
            handLiveDataEvent(it)
        }
    }

    private fun handLiveDataEvent(event: BusEvent) {
        var user = event.data as UserEntity
        when(event.type){
            101 ->{
                mDataBinding.etAccount.setText(user.username)
                mDataBinding.etPassword.setText(user.password)
            }
        }
    }

    /**
     * 对于内容必须要做校验
     * 1.字符长度有限制
     * 2.字符内容有限制（大小写字母，下划线或特殊）
     * 3.字符内容涉政涉黄
     * 4.其他特殊限制
     */
    private fun loginToServer() {
        //校验一下输入的内容
        if (userName.isNullOrEmpty() || password.isNullOrEmpty()){
            showToastMsg("账号密码不能为空！")
            return
        }

        //校验是否为正常用户名
        if (!RegexUtils.isUsername(userName)){
            showToastMsg("账号输入不合法！")
            return
        }

        //开启协程发送意图
        lifecycleScope.launch {
            mViewModel.channel.send(AccountViewIntent.LoginToServer(userName, password))
        }
    }
    override suspend fun collectUIState() {
        mViewModel.uiState.collect{
            when(it){
                is AccountUiState.LoginToServerSuccess -> saveUserInfo(it.userEntity)
                is AccountUiState.LoginToServerFail -> showToastMsg(it.msg)
                else -> {}
            }
        }
    }

    private fun saveUserInfo(userEntity: UserEntity) {
        //保存用户信息
        userEntity.headImg = "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image"
        userEntity.nick = "哪吒2"
        MMKV.defaultMMKV().encode("userInfo", GsonUtils.toJson(userEntity))

        //保存Token信息
        if (!userEntity.token.isNullOrEmpty()){
            MMKV.defaultMMKV().encode("token", userEntity.token)
        }
        //发送用户更新事件
        LiveDataBus.getDefault<BusEvent>("update_user_info").value = BusEvent(userEntity, 100)

        //关闭当期页面
        finish()

    }


}